package component.velocity;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;


public class Test {

	static{
		Properties properties = new Properties();
		properties.setProperty("file.resource.loader.path", "D:/vm");
		properties.setProperty("input.encoding", "UTF-8");
		properties.setProperty("output.encoding", "UTF-8");
		/*properties.setProperty("class.resource.loader.class",
				"org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader");  */
		//初始化模板引擎
		Velocity.init(properties);
	}
	
	public static void outPutHtml(Template template, VelocityContext context) throws IOException {
		//创建输出文件
				File output = new File("D:/vm/1.html");
				if(!output.getParentFile().exists())
					output.getParentFile().mkdir();
				//创建输出流
				FileOutputStream outputStream = new FileOutputStream(output);
				OutputStreamWriter writer = new OutputStreamWriter(outputStream,"UTF-8");
				BufferedWriter bufferedWriter = new BufferedWriter(writer);
				template.merge(context, bufferedWriter);

				bufferedWriter.flush();
				outputStream.close();
				bufferedWriter.close();
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//获取VelocityContext
		VelocityContext context = new VelocityContext();
		//为Context设置变量
		context.put("title", "标题");
		context.put("author", "刘伯恩");
		context.put("top", "top内容");
		context.put("footer", "footer");
		//获取模板文件
		Template template = Velocity.getTemplate("test.vm");
		
		try {
			outPutHtml(template, context);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		/*StringWriter sw = new StringWriter();
		//使用模板文件的merge函数合并模板和context提供的变量，输出到StringWriter中
		template.merge(context, sw);
		sw.flush();
		System.out.println(sw.toString());*/

		
	}

}
